package gaboli.common.utils;

import javax.xml.bind.JAXB;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Utilities for converting JAXB-Annotated object instances to and from  XML.
 *
 * @author C. Burrell deltafront@gmail.com
 */
public class JaxbXmlUtils
{
    /**
     * Marshalls JAXB-annotated object to XML and returns the String.
     *
     * @param object - Object to be converted to XML String.
     * @return XML String.
     * @since 1.0
     */
    public String toXml( Object object )
    {
        OutputStream outputStream = new ByteArrayOutputStream();
        JAXB.marshal( object, outputStream );
        String xml = outputStream.toString();
        return xml;
    }

    /**
     * Deserializes XML to an instance of a JAXB-annotated object.
     *
     * @param xml xml to be derserialized.
     * @param c   class of Type <T> of which xml is a representation of.
     * @param <T> Type of which xml is a representation of.
     * @return instance of a JAXB-annotated object.
     * @since 1.0
     */
    public <T> T fromXML( String xml, Class<T> c )
    {
        InputStream input = new ByteArrayInputStream( xml.getBytes() );
        T out = JAXB.unmarshal( input, c );
        return out;
    }

}
